package view;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.JPanel;

public class OverlayContainer extends JPanel implements Drawable {

	private HashMap<String, Overlay> overlays;
	private ArrayList<Overlay> order;
	private BufferedImage img;
	private Dimension dimension;
	
	public OverlayContainer( Dimension dimension ) {
		super();
		overlays = new HashMap<String, Overlay>();
		order = new ArrayList<Overlay>();
		this.dimension = dimension;
	}
	
	public void draw( Graphics g ) {
		g.clearRect(0, 0, dimension.width, dimension.height);//clear drawing area
		
		for( Overlay o : order ) {
			for( String test : overlays.keySet() ) {
				if( overlays.get(test) == o ) {
					o.draw( g );
				}
			}
		}
		
//		for( Overlay o : overlays.values() ) {
//			o.draw( g );
//		}
	}
	
	public void paint( Graphics g ) {
		this.draw( g );
	}
	
	public Dimension getDimension() {
		return dimension;
	}
	
	public void setDimension(Dimension dimension) {
		this.dimension = dimension;
		for( Overlay o : overlays.values() ) {
			o.setOuterDimension(this.dimension);
		} //fix the order!
	}
	
	public int getOverlayCount() {
		return order.size();
	}
	
	public Overlay getOverlay( int position) {
		return order.get(position);
	}
	
	public Overlay getOverlay( String id) {
		return overlays.get(id);
	}
	
	public void addOverlay( String id, int position, Overlay overlay) {
		order.add(position, overlay);
		overlays.put(id, overlay);
	}
	
	public void addOverlay( String id, Overlay overlay) {
		order.remove( overlay );
		overlays.remove( id );
		order.add(overlay);
		overlays.put(id, overlay);
	}
	
	public Overlay removeOverlay(Overlay o) {
		order.remove(o);
		return this.removeFromHashMap(o);
	}
	
	public Overlay removeOverlay( int position ) {
		Overlay o = order.get(position);
		order.remove(position);//remove from order
		return this.removeFromHashMap(o);
	}
	
	public Overlay removeOverlay( String id ) {
		order.remove(overlays.get(id));//get the overlay from map and remove it from order
		return overlays.remove(id);
	}
	
	private Overlay removeFromHashMap(Overlay o) {
		for( String id : overlays.keySet()) {//go through all keys
			if (overlays.get(id) == o) {//if it is the overlay to remove
				return overlays.remove(id);//then remove it
			}
		}
		return null;
	}
	
}
